package com.gljx.web.controller;


import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class ExitClazzController {

    @Autowired
    private ExitClazzService exitClazzService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ExitClazzEntryService exitClazzEntryService;

    @Autowired
    private StudentController studentController;

    @Autowired
    private WithholdItemService withholdItemService;

    @Autowired
    private CustomLogService customLogService;

    @Autowired
    private StudentService studentService;

    @Resource
    private HistoryService historyService;

    @Resource
    private TaskService taskService;

    ActitiviUtil actitiviUtil = new ActitiviUtil();

    /**
     * 查询退班申请
     *
     * @param request
     * @return
     * @throws Exception
     * @createTime 2017-11-20 3:06 pm
     * @author zyq.
     */
    @RequestMapping(value = "/selExitClazz/look.action")
    public String selExitClazz(HttpServletRequest request) throws Exception {
        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.DATE, -1);// 月份减1
        Date resultDate = ca.getTime(); // 结果
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");                                   //获取已经登录用户数据
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());   //获取登录用户组织ID
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());
        PageBean<ExitClazz> pBean = getPageBean(request, department.getFid(), beginTime, endTime);
        //		rhc  信息总条数
        String messageAmount="共有"+pBean.getTr()+"条信息";
        request.setAttribute("pb", pBean);
        request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);
        request.setAttribute("ActivitiKey", ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc);
        request.setAttribute("exitClazzs", pBean.getBeanList());
        //		rhc  信息总条数
        request.setAttribute("messageAmount",messageAmount);
        return "backHome/exitClazz/exitClazzList";
    }


    /**
     * 查询详情
     *
     * @param request
     * @param fid
     * @return
     * @createTime 2017-11-20 3:06 pm
     * @author zyq.
     */
    @ResponseBody
    @RequestMapping(value = "/selExitClazzEntry")
    public List<ExitClazzEntry> selExitClazzEntry(HttpServletRequest request, String fid) {
        List<ExitClazzEntry> clazzEntries = exitClazzEntryService.selExitClazzByFid(fid);
        return clazzEntries;
    }


    /**
     * 进入新增退班申请
     *
     * @param request
     * @return
     * @throws Exception
     * @createTime 2017-11-22 11:06 am
     * @author zyq.
     */
    @RequestMapping(value = "/addExitClazz")
    public String addExitClazz(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.DATE, -1);// 月份减1
        Date resultDate = ca.getTime(); // 结果
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginTime = sdf.format(resultDate);
        String endTime = sdf.format(new Date());
        User user = (User) session.getAttribute("user");                                        //获取已经登录用户数据
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());       //获取登录用户组织ID
        //Map map = studentController.getPageAsTrainCharge(request, "", "", "0", beginTime, endTime); //调用学员方法    //调用学员方法
        Map map = studentController.getPageAsTrainCharge(request, "","","0", "", "","", beginTime, endTime); //调用学员方法
        request.setAttribute("flag", 1);                //是否为新增记录
        request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);
        request.setAttribute("pb", map.get("pb"));
        request.setAttribute("students", map.get("sList"));
        request.setAttribute("department", department);
        return "backHome/exitClazz/detailExitClazz";
    }


    /**
     * 查询扣款项目
     *
     * @return
     * @createTime 2017-11-22 11:06 am
     * @author zyq.
     */
    @ResponseBody
    @RequestMapping(value = "/selectWithHoldItem")
    public List<WithholdItem> selectWithHoldItem(HttpServletRequest request) {
        List<WithholdItem> lWithholdItems = withholdItemService.selectWithholdItemAll();
        return lWithholdItems;
    }


    /**
     * 根据姓名查询扣款项目
     *
     * @param name
     * @return
     * @createTime 2017-11-22 1:06 pm
     * @author zyq.
     */
    @ResponseBody
    @RequestMapping(value = "/selectWithHoldItemByName")
    public List<WithholdItem> selectWithHoldItemByName(String name) {
        List<WithholdItem> lWithholdItems = withholdItemService.selectWithHoldItemByName(name);
        return lWithholdItems;
    }


    /**
     * 新增退班申请
     *
     * @param request
     * @param exitClazzEntry ExitClazzEntry对象
     * @param clazz          ExitClazz对象
     * @return
     * @createTime 2017-11-22 4:36 pm
     * @author zyq.
     */
    @RequestMapping(value = "/saveExitClazz")
    public String saveExitClazz(HttpServletRequest request, ExitClazzEntry exitClazzEntry, ExitClazz clazz, String cfamount1, String state) {
        if (state.equals("3")) {
            //获取操作人信息
            User user = (User) request.getSession().getAttribute("user");
            //利用UUID生成fid
            clazz.setFid(GetFid.UUIDIntoFid());
            //控制单元id
            clazz.setFcontrolunitid(user.getFcompanyid());
            //创建人id
            clazz.setFcreatorid(user.getFid());
            //公司id
            clazz.setCfficompanyid(user.getFcompanyid());
            //获取当前时间
            String createTime = TimeFormat.timeFormat(new Date());
            clazz.setFcreatetime(createTime);
            /*String fnumber = customLogService.selectFunmber("CT_DS_DROPOUTAPPLY",user.getFcompanyid());	*/           //获取最后一个编号
            clazz.setFnumber(GetFnumber.fnumbers("TX"));                               //获取编码
            clazz.setFhandlerid(user.getFid());
            clazz.setCfbillstate((long) 3);
            exitClazzService.insertExitClazz(clazz);
            if (exitClazzEntry.getCfkkxmid() == null) {

            } else {
                String[] fid = exitClazzEntry.getCfkkxmid().split(",");                            //扣款项目
                String[] prices = cfamount1.split(",");                                                //扣款项目金额
                for (int i = 0; i < fid.length; i++) {
                    if (prices[i] == null) {
                        BigDecimal price = null;
                        exitClazzEntry.setCfamount(price);
                    } else {
                        BigDecimal price = new BigDecimal(prices[i]);
                        exitClazzEntry.setCfamount(price);
                    }
                    exitClazzEntry.setFparentid(clazz.getFid());
                    exitClazzEntry.setCfkkxmid(fid[i]);
                    exitClazzEntry.setFid(GetFid.UUIDIntoFid());
                    exitClazzEntryService.insertExitClazzEntry(exitClazzEntry);
                }
            }
            List<Student> students = studentService.selectStudentByFid(clazz.getCfstudentid());
            if (!students.isEmpty())
                customLogService.addLog("退学申请", "办理了学员:" + students.get(0).getFnumber() + clazz.getStudentName() + "退学申请,单据编号：" + clazz.getFnumber(), clazz.getCfstudentid(), user.getFid());
        } else {
			/*//获取操作人信息
			User user = (User) request.getSession().getAttribute("user");
			//利用UUID生成fid
			clazz.setFid(GetFid.UUIDIntoFid());
			//控制单元id
			clazz.setFcontrolunitid(user.getFcompanyid());
			//创建人id
			clazz.setFcreatorid(user.getFid());
			//公司id
			clazz.setCfficompanyid(user.getFcompanyid());
			//获取当前时间
			String createTime = TimeFormat.timeFormat(new Date());
			clazz.setFcreatetime(createTime);
			*//*String fnumber = customLogService.selectFunmber("CT_DS_DROPOUTAPPLY",user.getFcompanyid());	*//*           //获取最后一个编号
			clazz.setFnumber(GetFnumber.fnumbers("TX"));                               //获取编码
			clazz.setFhandlerid(user.getFid());
			clazz.setCfbillstate((long) 4);
			exitClazzService.insertExitClazz(clazz);
			String [] fid = exitClazzEntry.getCfkkxmid().split(",");                            //扣款项目
			String[] prices = cfamount1.split(",");												//扣款项目金额
			for(int i=0;i<fid.length;i++){
				if(prices[i] == null){
					BigDecimal price = null;
					exitClazzEntry.setCfamount(price);
				}else {
					BigDecimal price = new BigDecimal(prices[i]);
					exitClazzEntry.setCfamount(price);
				}
				exitClazzEntry.setFparentid(clazz.getFid());
				exitClazzEntry.setCfkkxmid(fid[i]);
				exitClazzEntry.setFid(GetFid.UUIDIntoFid());
				exitClazzEntryService.insertExitClazzEntry(exitClazzEntry);
			}
			exitClazzService.submitFlow(clazz, submitFlag);
			customLogService.addLog("退学申请", clazz.getStudentName()+"  "+createTime + "办理了退学申请",clazz.getCfstudentid(), user.getFid());*/
        }
        request.setAttribute("type", 2);
        request.getSession().setAttribute("deptName", clazz.getDeptName());
        return "forward:addExitClazz";
    }

    /**
     * 修改页提交
     *
     * @return
     */
    @RequestMapping(value = "/submitFlowOnUpdate")
    @ResponseBody
    public Boolean submitFlowOnUpdate(String fnumber, HttpServletRequest request, String fid, String submitFlag, String deptName) {
        User user = (User) request.getSession().getAttribute("user");
        ExitClazz exitClazz = new ExitClazz();
        exitClazz.setFid(fid);
        exitClazz.setFnumber(fnumber);
        exitClazz.setDeptName(deptName);
        exitClazz.setCfbillstate((long) 4);
        ExitClazz clazz = exitClazzService.selExitClazzById(fid);
        exitClazzService.submitFlow(exitClazz, submitFlag, request);
        exitClazzService.updateExitClazz(exitClazz);
        List<Student> students = studentService.selectStudentByFid(clazz.getCfstudentid());
        if (clazz != null)
            if (!students.isEmpty())
                customLogService.addLog("退学申请", "提交了学员:" + students.get(0).getFnumber() + clazz.getStudentName() + "退学申请,单据编号：" + clazz.getFnumber(), clazz.getCfstudentid(), user.getFid());
        return true;
    }

    /**
     * 进入修改退班申请
     *
     * @param request
     * @param fid
     * @return
     * @throws Exception
     * @createTime 2017-11-23 10:16 am
     * @author zyq.
     */
    @RequestMapping(value = "/selExitClazzById")
    public String selExitClazzById(HttpServletRequest request, String fid) throws Exception {
        fid = fid.replace(" ", "+");
        ExitClazz exitClazz = exitClazzService.selExitClazzById(fid);
        List<ExitClazzEntry> exitClazzEntries = exitClazzEntryService.selExitClazzByFid(fid);
       Student student= studentService.queryStudentByIdCardNoWx(exitClazz.getCfidcardno().toString());
        if (exitClazz == null)
            return "/error/not_data";
        else {
            if (exitClazz.getCfbillstate() == 3) {
                Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
                ca.setTime(new Date()); // 设置时间为当前时间
                ca.add(Calendar.DATE, -1);// 月份减1
                Date resultDate = ca.getTime(); // 结果
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String beginTime = sdf.format(resultDate);
                String endTime = sdf.format(new Date());
                Map map = studentController.getPageAsTrainCharge(request, "", "", "0","","","", beginTime, endTime); //调用学员方法 //调用学员方法
                request.setAttribute("exitClazz", exitClazz);
                request.setAttribute("exitClazzEntries", exitClazzEntries);
                request.setAttribute("beginTime", beginTime);
                request.setAttribute("endTime", endTime);
                request.setAttribute("pb", map.get("pb"));
                request.setAttribute("students", map.get("sList"));
                request.setAttribute("flag", 2);
            } else {
                request.setAttribute("exitClazz", exitClazz);
                request.setAttribute("exitClazzEntries", exitClazzEntries);
                request.setAttribute("flag", 2);
            }

            String fnumberName = ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc;
            String fnumber = (String) exitClazz.getFnumber();
            List<Object> activities = getActivities(fnumberName, fnumber);
            request.setAttribute("activities", activities);
            ExitClazz exitClazzTime = new ExitClazz();
            exitClazzTime.setFid(fid);
            exitClazzTime.setCfaudittime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//            request.getSession().setAttribute("deptName", exitClazz.getDeptName());
            //2.查询
            String result = actitiviUtil.getTaskStateByUser(
                    ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc, exitClazz.getFnumber()               //单据
            );
            String seeFlag = exitClazzService.selectAuditPersonByAdd(exitClazz.getFnumber(), result);
            request.setAttribute("seeFlag", seeFlag);
            request.setAttribute("ActivitiKey", ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc);
            request.setAttribute("submitFlag", result);
//         String deptName=()request.getSession().getAttribute("deptName");
            request.setAttribute("deptName", student.getCfdepartment());
            return "backHome/exitClazz/detailExitClazz";
        }

    }

    /**
     * 退学审核流程
     *
     * @param fnumberName 流程名
     * @param fnumber     单据
     * @return
     * @throws IllegalAccessException
     */
    public List<Object> getActivities(String fnumberName, String fnumber) throws IllegalAccessException {
        //结果集
        List<Object> results = new ArrayList<>();
        if (StringUtils.isEmpty(fnumber) || StringUtils.isEmpty(fnumberName)) {
            return results;
        }
        //流程实例
        List<HistoricProcessInstance> list = historyService
                .createHistoricProcessInstanceQuery()
                .variableValueEquals(fnumberName, fnumber)
                .orderByProcessInstanceEndTime().asc()
                .list();
        if (list == null || list.size() <= 0) {
            return results;
        }
        List<HistoricTaskInstance> tasklist =
                historyService
                        .createHistoricTaskInstanceQuery()
                        .processInstanceId(list.get(list.size() - 1).getId())
                        .orderByHistoricTaskInstanceEndTime().asc()
                        .list();
        //当前流程的批註
        List<Comment> commentList = taskService.getProcessInstanceComments(list.get(list.size() - 1).getId());
        //将任务信息和批注装载
        for (int i = 0; i < tasklist.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            //历史任务
            HistoricTaskInstance task = tasklist.get(i);
            for (int j = 0; j < commentList.size(); j++) {
                //循环的批注
                Comment comment = commentList.get(j);
                //当批注的任务ID等于任务的ID时将数据装载
                if (tasklist.get(i).getId()
                        .equals(commentList.get(j).getTaskId())) {
                    map.put("Name", task.getName());
                    map.put("FullMessage", comment.getFullMessage());
                    map.put("FullMessage2", "同意");
                    map.put("User", comment.getUserId());
                    map.put("Time", CommonUtil.dateToDate(comment.getTime()));
                    results.add(map);
                    if (!comment.getFullMessage().substring(0, 2).equals("同意")) {
                        results.clear();
                    }
                }
            }
        }
        return results;
    }

    /**
     * 更新转班申请
     *
     * @param request
     * @param exitClazzEntry 退班副表
     * @param clazz          退班主表
     * @param cfamount1      金额
     * @return
     * @throws Exception
     * @createTime 2017-11-23 1:54 pm
     * @author zyq.
     */
    @RequestMapping(value = "/updateExitClazz")
    public String updateExitClazz(HttpServletRequest request, ExitClazzEntry exitClazzEntry, ExitClazz clazz, String cfamount1) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        String[] fids = clazz.getFid().split(",");
        String updateTime = TimeFormat.timeFormat(new Date());
        clazz.setFlastupdatetime(updateTime);
        clazz.setFlastupdateuserid(user.getFid());
        exitClazzService.updateExitClazz(clazz);
        exitClazzEntryService.delExitClazzById(fids);
        if (exitClazzEntry.getCfkkxmid() == null) {

        } else {
            String[] fid = exitClazzEntry.getCfkkxmid().split(",");                            //扣款项目
            String[] prices = cfamount1.split(",");                                                //扣款项目金额
            for (int i = 0; i < fid.length; i++) {
                BigDecimal price = new BigDecimal(prices[i]);
                exitClazzEntry.setFparentid(clazz.getFid());
                exitClazzEntry.setCfkkxmid(fid[i]);
                exitClazzEntry.setCfamount(price);
                exitClazzEntry.setFid(GetFid.UUIDIntoFid());
                exitClazzEntryService.insertExitClazzEntry(exitClazzEntry);
            }
        }
        List<Student> students = studentService.selectStudentByFid(clazz.getCfstudentid());
        if (clazz != null)
            if (!students.isEmpty())
                customLogService.addLog("退学申请", "修改了学员:" + students.get(0).getFnumber() + clazz.getStudentName() + "退学申请,单据编号：" + clazz.getFnumber(), clazz.getCfstudentid(), user.getFid());
        selExitClazz(request);
        request.setAttribute("type", 2);
        return "backHome/exitClazz/exitClazzList";
    }


    /**
     * 审核退班申请
     *
     * @param request
     * @param fid
     * @return
     * @throws Exception
     * @createTime 2017-11-23 5:24 pm
     * @author zyq.
     */
    @RequestMapping(value = "/checkExitClazzBillState")
    @ResponseBody
    public ServerResponse checkExitClazzBillState(HttpServletRequest request,
                                                  @RequestParam(defaultValue = "1", value = "agreed") String agreed,
                                                  String auditcomment, String fid, String fnumber,
                                                  @RequestParam(defaultValue = "5", value = "state") String state, String submitFlag) throws Exception {
		/*User user = (User) request.getSession().getAttribute("user");
		ExitClazz exitClazz = new ExitClazz();
				  exitClazz.setFid(fid);
				  exitClazz.setCfbillstate((long) 5);
				  exitClazz.setFauditorid(user.getFid());
		ExitClazz exitClazz2 = exitClazzService.selExitClazzById(fid);
		Student student = new Student();
				student.setFid(exitClazz2.getCfstudentid());
				student.setCfstudentstate((long) 11);           //修改学员状态
		exitClazzService.updateExitClazz(exitClazz);
		studentService.updateStudentSelective(student);
		selExitClazz(request);
		customLogService.addLog("退学申请", user.getName() + TimeFormat.timeFormat(new Date()) + " 审核了转班申请 ", exitClazz2.getCfstudentid(), user.getFid());  //生成日志*/
        User user = (User) request.getSession().getAttribute("user");
        ExitClazz exitClazz2 = exitClazzService.selExitClazzById(fid);
        ExitClazz exitClazz = new ExitClazz();
        exitClazz.setFid(fid);
        exitClazz.setFauditorid(user.getFid());
        exitClazz.setFnumber(fnumber);
        exitClazz.setCfstudentid(exitClazz2.getCfstudentid());
        List<Student> students = studentService.selectStudentByFid(exitClazz2.getCfstudentid());
        if ("3".equalsIgnoreCase(state))
            if (!students.isEmpty())
                customLogService.addLog("退学申请", "反审核了学员:" + students.get(0).getFnumber() + exitClazz2.getStudentName() + "退学申请,单据编号：" + exitClazz2.getFnumber(), exitClazz2.getCfstudentid(), user.getFid());
            else
                customLogService.addLog("退学申请", "审核了学员:" + students.get(0).getFnumber() + exitClazz2.getStudentName() + "退学申请,单据编号：" + exitClazz2.getFnumber(), exitClazz2.getCfstudentid(), user.getFid());
        return ServerResponse.createBySuccessMessage(exitClazzService.checkExitClazz(exitClazz, state, agreed, auditcomment, submitFlag, request));
    }


    /**
     * 批量删除退班申请
     *
     * @param fid
     * @param request
     * @return
     * @throws Exception
     * @createTime 2017-11-23 9:36 am
     * @author zyq.
     */
    @RequestMapping(value = "/delExitClazzById")
    public String delExitClazzById(String fid, HttpServletRequest request) throws Exception {
        String[] fids = fid.split(",");
//        User user = (User) request.getSession().getAttribute("user");
//        for (int i = 0; i < fids.length; i++) {
//            Student student = new Student();
//            ExitClazz exitClazz = exitClazzService.selExitClazzById(fids[i]);
//            List<Student> list = studentService.selectStudentByFid(exitClazz.getCfstudentid());
//            if (!list.isEmpty())
//                student = list.get(0);
//            customLogService.addLog("退学申请", "删除了学员:" + student.getFnumber() + student.getFnameL2() + "的退学申请,单据编号：" + exitClazz.getFnumber(), student.getFid(), user.getFid());
//        }
//        exitClazzService.delExitClazzById(fids);
//        exitClazzEntryService.delExitClazzById(fids);
       ExitClazz exitClazz = exitClazzService.selExitClazzById(fid);
        actitiviUtil.deleteTask(ActivitiKey.DrivingSys_exitClazz_nc,exitClazz.getFnumber());
        System.out.println("已经删除流程");
//        selExitClazz(request);
        return "backHome/exitClazz/exitClazzList";
    }


    /**
     * 根据条件查询转班申请
     *
     * @param request
     * @param exitClazz 页面转递对象
     * @param beginTime 页面时间
     * @param endTime
     * @return
     * @throws Exception
     * @createTime 2017-11-23 9:49 am
     * @author zyq.
     */
    @RequestMapping(value = "/selExitClazzByCon")
    public String selExitClazzByCon(HttpServletRequest request, ExitClazz exitClazz, String beginTime, String endTime) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");                                   //获取已经登录用户数据
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());   //获取登录用户组织ID
        PageBean<ExitClazz> pBean = getPageBean1(request, department.getFid(), beginTime, endTime, exitClazz, false);
        String messageAmount="共有"+pBean.getTr()+"条信息";
        request.setAttribute("pb", pBean);
        request.setAttribute("beginTime", beginTime);
        request.setAttribute("endTime", endTime);
        request.setAttribute("exitClazzs", pBean.getBeanList());
        request.setAttribute("exitClazz1", exitClazz);
        request.setAttribute("ActivitiKey", ActivitiKey.Driving_GL_ID.equals(GetUserSession.getUserSession(request)) ? ActivitiKey.DrivingSys_exitClazz_gl : ActivitiKey.DrivingSys_exitClazz_nc);
        request.setAttribute("messageAmount",messageAmount);
        return "backHome/exitClazz/exitClazzList";
    }


    @RequestMapping(value = "/outExitClazzExcel")
    public void outExitClazzExcel(HttpServletResponse response, HttpServletRequest request,
                                  ExitClazz exitClazz, String beginTime, String endTime) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        List<Object> data = new ArrayList<>();
        //查询数据
        PageBean<ExitClazz> pBean = getPageBean1(request, user.getFcompanyid(), beginTime, endTime, exitClazz, true);
        for (ExitClazz exitClazz1 : pBean.getBeanList()) {
            data.add(exitClazz1.getFnumber());//业务日期
            data.add(exitClazz1.getFbizdate());
            data.add(exitClazz1.getFdescription());//制单人名称
            data.add(exitClazz1.getFauditorName());//学员
            data.add(exitClazz1.getFhandlerName());//学员编码
            data.add(exitClazz1.getStudentName());//身份证号
            data.add(exitClazz1.getCfidcardno());
            data.add(exitClazz1.getCftjr());
            data.add(exitClazz1.getCfbmsj());
            if (exitClazz1.getCfbillstate() == 3) {
                data.add("保存");//单据状态
            } else if (exitClazz1.getCfbillstate() == 4) {
                data.add("提交");//单据状态
            } else if (exitClazz1.getCfbillstate() == 5) {
                data.add("审核");//单据状态
            } else {
                data.add("");//单据状态
            }
            if ("1".equals(exitClazz1.getCfguifei()))
                data.add("已付");
            else if ("2".equals(exitClazz1.getCfguifei()))
                data.add("未付");
            else if ("3".equals(exitClazz1.getCfguifei()))
                data.add("已抵规费");
            else
                data.add("");
            if ("1".equals(exitClazz1.getCfkmy()))
                data.add("及格");
            else if ("2".equals(exitClazz1.getCfkmy()))
                data.add("未考");
            else if ("3".equals(exitClazz1.getCfkmy()))
                data.add("不及格");
            else if ("4".equals(exitClazz1.getCfkmy()))
                data.add("未到");
            else
                data.add("");
            if ("1".equals(exitClazz1.getCfkme()))
                data.add("及格");
            else if ("2".equals(exitClazz1.getCfkme()))
                data.add("未考");
            else if ("3".equals(exitClazz1.getCfkme()))
                data.add("不及格");
            else if ("4".equals(exitClazz1.getCfkme()))
                data.add("未到");
            else
                data.add("");
            if (exitClazz1.getCfjsk() == 1) {
                data.add("已发放");//单据状态
            } else if (exitClazz1.getCfjsk() == 2) {
                data.add("未发放");//单据状态
            } else {
                data.add("");//单据状态
            }
            data.add(exitClazz1.getCfhjgk());
            data.add(exitClazz1.getCfyt());
            data.add(exitClazz1.getCfkkxmName());
            data.add(exitClazz1.getCfamount());
            if ("1".equals(exitClazz1.getCfypkxt())) {
                data.add("已录");//单据状态
            } else if ("2".equals(exitClazz1.getCfypkxt())) {
                data.add("未录");//单据状态
            } else {
                data.add("");//单据状态
            }
            data.add(exitClazz1.getCfpxf());
            data.add(exitClazz1.getCfgf());
            data.add(exitClazz1.getCfclazz());
            data.add(exitClazz1.getCfyinshou());
            data.add(exitClazz1.getCfyishou());
            data.add(exitClazz1.getCfyouhui());
            data.add(exitClazz1.getCfqianfei());
            data.add(exitClazz1.getCfshuaka());
        }
        //头部数据
        String head[] = {"单据编号", "业务日期", "退学原因", "审核人名称", "制单人名称", "学员", "身份证号码", "推荐人", "报名时间", "单据状态", "规费状态",
                "科目一", "科目二", "计时卡", "合计共扣", "应退金额", "扣款项目", "金额", "约排考系统", "培训费", "规费", "班级", "应收金额", "已收金额", "优惠金额", "欠费金额", "刷卡金额"};
        //长度
        Integer length[] = {7000, 3000, 7000, 2000, 2000, 3000, 6500, 2200, 4000, 2000, 2000, 2600, 4000, 4000, 3000, 2000, 3000, 3000, 2000, 2000, 2000, 3000, 2000, 2000, 2000, 2000, 2000, 2000};
        try {
            //导出Excel
            CommonExport.importExcel(response, "退学申请" + TimeFormat.getNowTime2() + ".xls", "退学申请", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @SuppressWarnings("unchecked")
    /**
     * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
     * @return 返回PageBean实体类
     * @throws Exception
     */
    public PageBean<ExitClazz> getPageBean(HttpServletRequest request, String fid, String beginTime, String endTime) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        String psql = "select  T.FID,to_char(t.FCREATETIME,'YYYY-MM-DD HH24:MI:SS') fcreatetime,"
                + "to_char(t.FLASTUPDATETIME,'YYYY-MM-DD HH24:MI:SS') flastupdatetime,"
                + "to_char(t.FBIZDATE,'yyyy-MM-DD')  fbizdate,"
                + "to_char(T.CFBMSJ,'YYYY-MM-DD')  cfbmsj,"
                + "T.FCREATORID, T.FCONTROLUNITID, T.FNUMBER, T.FHANDLERID, T.FDESCRIPTION, T.FHASEFFECTED, T.FAUDITORID, T.FSOURCEBILLID,"
                + "T.FSOURCEFUNCTION, T.FFIVOUCHERED, T.CFFICOMPANYID, T.CFSTUDENTID, T.CFIDCARDNO, "
                + "T.CFTJR,T.CFBILLSTATE,"
                + "T.CFGUIFEI,T.CFKMY, T.CFKME, T.CFJSK, T.CFHJGK, T.CFYT, T.CFYPKXT, T.CFGF, T.CFPXF, T.CFYISHOU, "
                + "T.CFQIANFEI, T.CFYOUHUI, T.CFYINSHOU, T.CFCLAZZ, T.CFSHUAKA,"
                + "U.FNAME_L2 AS STUDENTNAME,S.NAME AS FCREATENAME,S1.NAME AS FLASTUPDATENAME,S2.NAME AS FHANDLERNAME,S3.NAME AS FAUDITORNAME"
                + "  FROM CT_DS_DROPOUTAPPLY T LEFT JOIN  CT_DS_STUDENT U ON T.CFSTUDENTID=U.FID"
                + " LEFT JOIN T_E_USER S ON T.FCREATORID=S.FID LEFT JOIN T_E_USER S1 ON T.FLASTUPDATEUSERID=S1.FID "
                + " LEFT JOIN T_E_USER S2 ON T.FHANDLERID=S2.FID LEFT JOIN T_E_USER S3 ON T.FAUDITORID=S3.FID "
                + " WHERE t.CFFICOMPANYID= '" + fid + "' and to_char(t.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + " ' AND '" + endTime + "'";
        psql += "order by to_char(t.FBIZDATE,'yyyy-MM-dd') desc";
        int psize = 10; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = exitClazzService.selectPage(pindex, psql, psize);
        PageBean<ExitClazz> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<ExitClazz>) paramMap.get("v_cur")); //每页数据集
        return pb;

    }


    @SuppressWarnings("unchecked")
    /**
     * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
     * @return 返回PageBean实体类
     * @throws Exception
     */
    public PageBean<ExitClazz> getPageBean1(HttpServletRequest request, String fid, String beginTime, String endTime, ExitClazz exitClazz, boolean isExcel) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        String psql = "select  T.FID,  "
                + "to_char(t.FBIZDATE,'yyyy-MM-DD')  fbizdate,"
                + "to_char(T.CFBMSJ,'YYYY-MM-DD')  cfbmsj,"
                + "T.FCREATORID,T.CFAUDITTIME,T.FCONTROLUNITID, T.FNUMBER, T.FHANDLERID, T.FDESCRIPTION, T.FHASEFFECTED, T.FAUDITORID, T.FSOURCEBILLID,"
                + "T.FSOURCEFUNCTION, T.FFIVOUCHERED, T.CFFICOMPANYID, T.CFSTUDENTID, T.CFIDCARDNO, "
                + "T.CFTJR,T.CFBILLSTATE,"
                + "T.CFGUIFEI,T.CFKMY, T.CFKME, T.CFJSK, T.CFHJGK, T.CFYT, T.CFYPKXT, T.CFGF, T.CFPXF, T.CFYISHOU, "
                + "T.CFQIANFEI, T.CFYOUHUI, T.CFYINSHOU, T.CFCLAZZ, T.CFSHUAKA,"
                + "U.FNAME_L2 AS STUDENTNAME,U.FNUMBER AS STUDENTNUMBER,U.CFSLZJCXDH AS STUDENTCFSLZJCXDH,U.CFDEPARTMENT,S.NAME AS FCREATENAME," +
                "S1.NAME AS FLASTUPDATENAME,S2.NAME AS FHANDLERNAME,S3.NAME AS FAUDITORNAME";
        if (isExcel)
            psql += ",D.CFAMOUNT ,W.FNAME_L2 AS CFKKXMNAME";
        psql += "  FROM CT_DS_DROPOUTAPPLY T ";
        psql += " LEFT JOIN  CT_DS_STUDENT U ON T.CFSTUDENTID=U.FID";
        psql += " LEFT JOIN T_E_USER S ON T.FCREATORID=S.FID LEFT JOIN T_E_USER S1 ON T.FLASTUPDATEUSERID=S1.FID ";
        psql += " LEFT JOIN T_E_USER S2 ON T.FHANDLERID=S2.FID LEFT JOIN T_E_USER S3 ON T.FAUDITORID=S3.FID ";
        if (isExcel)
            psql += "LEFT JOIN CT_DS_DROPOUTAPPLYENRTY D ON D.FPARENTID = T.FID LEFT JOIN CT_DS_WITHHOLDITEM W ON D.CFKKXMID = W.FID";

        psql += " WHERE t.CFFICOMPANYID= '" + fid + "' ";
        if (exitClazz.getFnumber().equals(null) || exitClazz.getFnumber() == "") {

        } else {
            psql += "and T.FNUMBER like '%" + exitClazz.getFnumber() + "%'";
        }
        if (exitClazz.getCfidcardno().equals(null) || exitClazz.getCfidcardno() == "") {

        } else {
            psql += "and t.cfidcardno like '%" + exitClazz.getCfidcardno() + "%'";
        }
        if (exitClazz.getStudentName().equals(null) || exitClazz.getStudentName() == "") {

        } else {
            psql += "and u.fname_l2 like '%" + exitClazz.getStudentName() + "%'";
        }
        if (beginTime.equals(null) || beginTime.equals("") || endTime.equals(null) || endTime.equals("")) {
        } else {
            psql += "and to_char(t.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'";
        }
        psql += "order by to_char(t.FBIZDATE,'yyyy-MM-dd') desc";
        int psize = 0;
        Map<String, Object> paramMapCount = getPageBeanCount(psql); //取记录总数
        if (isExcel) {
            if ((int) paramMapCount.get("Pcount") == 0)
                psize = 1;
            else
                psize = (int) paramMapCount.get("Pcount");
        } else {
            psize = 80; //每页显示数
        }
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = exitClazzService.selectPage(pindex, psql, psize);
        PageBean<ExitClazz> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<ExitClazz>) paramMap.get("v_cur")); //每页数据集
        return pb;

    }

    /**
     * 取记录总数 dmz 20160921
     *
     * @param psql SQL语句
     * @return Map
     * @throws Exception
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = exitClazzService.selectPageCount(psql);
        return paramMap;
    }

}
